/**
 * create by young (young2f@outlook.com) on 2019/1/17
 */
'use strict';
const StringDecoder = require('string_decoder').StringDecoder;
const uuid = require('uuid');
const crypto = require('crypto');
const moment = require('moment');

function getUUID() {
    return uuid.v1()
        .toUpperCase()
        .split('-')
        .join('');
}

function getCode(prefix) {
    const time = moment()
        .format('YYMMDDHHmmss');
    const size = 4;
    const id = uuid.v4();
    id.toString()
        .replace(/\-/g, '');
    const temp = id.slice(0, size)
        .toUpperCase();
    return `${prefix}${time}${temp}`;
}

function getCryptoPassword(password) {
    const crypto = require('crypto');
    try {
        const hash = crypto.createHash('sha256');// sha256或者md5
        hash.update(password);
        return hash.digest('hex');
    } catch (e) {
        console.error(e);
        return password;
    }
}

/**
 * 获取N位随机数
 * @param n
 * @returns {number}
 */
function getRandom(n) {
    if (n === undefined) n = 8;
    return parseInt((Math.random() + 1) * Math.pow(10, n - 1));
}

function str2json(str, isDebug) {
    try {
        if (typeof str === 'object') {
            return str;
        }
        if (typeof str === 'array') {
            return str;
        }
        if (str === undefined || str === null || str === '') {
          //  console.error('str2json error:str is null');
            return;
        }
        if (typeof str === 'string') {
            return JSON.parse(str);
        }
        const key = '{\\';
        if (str.startsWith(key)) {
            str = str.replace(/[\\]/g, '');
        }
        let json = JSON.parse(str);

        if (typeof json === 'string') {
            json = eval('(' + json + ')');
            return str2json(json);
        }
        return json;
    } catch (e) {
      //  console.error('str2json error', str);
        return undefined;
    }
}

function string2array(str) {
    try {
        //  str=str.replace(/[\\]/g,'');
        JSON.parse(str);
    } catch (e) {
        return undefined;
    }
}

function buffer2str(buffer) {
    try {
        const decoder = new StringDecoder('utf8');
        return decoder.write(buffer);
    } catch (e) {
        return undefined;
    }
}

function buffer2json(buffer) {
    try {
        const decoder = new StringDecoder('utf8');
        let str = decoder.write(buffer);

        return str2json(str);
    } catch (e) {
        return undefined;
    }
}

function getDevId(deviceSpecCode, deviceCode) {
    if (deviceSpecCode === undefined) return undefined;
    if (deviceCode === undefined) return undefined;
    return '/' + deviceSpecCode + '/' + deviceCode;
}


/**
 * 使用Hmac256加密
 * @param encryptText 要加密的内容
 * @param secret 秘钥
 * @returns {string}
 */
function sha256Hmac(encryptText, secret) {
    try {
        return crypto.createHmac('sha256', secret)
            .update(encryptText)
            .digest('hex')
            .toUpperCase();
    } catch (e) {
        console.log('sha256Hmac crypto error,', e);
    }
    // try {
    //
    //   return crypto.createHmac('HmacSHA256', secret)
    //     .update(encryptText)
    //     .digest('hex')
    //     .toUpperCase();
    // } catch (e) {
    //   console.log('sha256Hmac crypto error,', e);
    // }
}

function getDevIdFromDevice(device) {
    const {deviceSpecCode, deviceSpecId, deviceCode} = device;
    if (deviceSpecId !== undefined) {
        return getDevId(deviceSpecId, deviceCode);
    }
    return getDevId(deviceSpecCode, deviceCode);
}

function str2int(str, defaultValue) {
    try {
        return parseInt(str);
    } catch (e) {
        return defaultValue;
    }
}

module.exports = {
    getCryptoPassword,
    getRandom,
    getCode,
    getUUID,
    str2json,
    buffer2json,
    sha256Hmac,
    buffer2str,
    string2array,
    str2int,
    getDevId,
    getDevIdFromDevice
};
